package cn.school.demo.ui.answer

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentAnswerEntryBinding
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken

class AnswerEntryFragment : Fragment() {

    private lateinit var viewModel: AnswerViewModel
    private lateinit var binging: FragmentAnswerEntryBinding
    private lateinit var map: Map<String, String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        map = GsonUtils.fromJson(
            arguments?.getString("map"),
            object : TypeToken<Map<String, String>>() {}.type
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        LogUtils.d(map)
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        viewModel = ViewModelProvider(this).get(AnswerViewModel::class.java)
        if (map.isNotEmpty()) {
            viewModel.setTitle(map["title"]!!)
            viewModel.setIntroduction(map["introduction"]!!)
        }
        binging =
            DataBindingUtil.inflate(inflater, R.layout.fragment_answer_entry, container, false)
        binging.vm = viewModel
        binging.vw = this
        binging.lifecycleOwner = viewLifecycleOwner
        return binging.root
    }

    fun gotoAnswerMain() {
        val title = when (map["title"]) {
            "每日答题" -> "每日党史答题"
            "每周答题" -> "每周党史答题"
            "专项答题" -> "专项党史答题"
            else -> map["title"]
        }
        val newMap = mapOf("title" to title, "introduction" to map["introduction"])
        val bundle: Bundle = bundleOf(Pair("map", GsonUtils.toJson(newMap)))
        MyApplication.goto(
            R.id.action_Answer_to_AnswerMain,
            findNavController(),
            parentFragmentManager,
            bundle
        )
    }

    fun gotoBack() {
        MyApplication.navigateThing["Answer"]?.let {
            MyApplication.goto(it.toInt(), findNavController(), parentFragmentManager)
        } ?: let {
            ToastUtils.showLong("系统错误！")
            MyApplication.goto(
                R.id.action_Answer_to_PartyHistoryAnswer,
                findNavController(),
                parentFragmentManager
            )
        }

    }
}